package com.app.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.app.common.Result;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.AdminUserService;
import com.app.service.BusinessService;
import com.app.service.CategoryService;
import com.app.service.OrderService;
import com.app.utils.CommonHelp;
import com.app.utils.StringTool;
import com.app.vo.OrderStatusCountsVO;
import com.app.vo.OrderVo;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.query.MPJQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * 订单
 *
 * @author 16693103420
 * @since 2024-01-31
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderModel> implements OrderService {

    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private VoucherRecordMapper voucherRecordMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private MessageBoxMapper messageBoxMapper;
    @Autowired
    private BusinessService businessService;


    @Override
    public OrderVo getUserOrderList(Integer page, Integer limit, Integer status, Integer userId, String businessName) {
        Page<OrderModel> page1 = new Page<>(page, limit);

        QueryWrapper<OrderModel> qw = new QueryWrapper<>();
        if (status != null) {
            qw.eq("status", status);
        }
        if (StringTool.isNotEmpty(businessName)) {
            qw.eq("business_name", businessName);
        }
        qw.eq("user_id", userId);
        qw.orderByDesc("create_time");
        Page<OrderModel> orderPage = orderMapper.selectPage(page1, qw);
        List<OrderModel> orderList = orderPage.getRecords();
        for (OrderModel orderModel : orderList) {
            Integer orderStatus = orderModel.getStatus();
            if (orderStatus == 1) {
                orderModel.setStatusName("待使用");
            }
            if (orderStatus == 2) {
                orderModel.setStatusName("待评价");
            }
            if (orderStatus == 3) {
                orderModel.setStatusName("已完成");
            }
            if (orderStatus == 4) {
                orderModel.setStatusName("已取消");
            }
            if (orderModel.getOrderReason() != null) {
                CategoryModel categoryModel = categoryService.getById(orderModel.getOrderReason());
                if (categoryModel != null) {
                    orderModel.setOrderReasonText(categoryModel.getName());
                }
            }
        }
        long count = orderPage.getTotal();
        OrderVo orderVo = new OrderVo();
        orderVo.setList(orderList);
        orderVo.setCount((int) count);
        return orderVo;
    }

    @Override
    public String userCancelOrder(OrderModel order, UserModel userModel) {
        ActivityModel activity = activityMapper.selectById(order.getActivityId());//活动信息

        Double price = order.getVoucher();

        String orderId = order.getOrderId();//订单号
        //生成益联券使用记录表
        VoucherRecordModel voucherRecordModel = new VoucherRecordModel();
        voucherRecordModel.setName(activity.getActivityName());
        voucherRecordModel.setTypeName("取消订单");
        String amountVoucher = "+" + price + "券";
        voucherRecordModel.setVoucher(amountVoucher);
        voucherRecordModel.setUserId(userModel.getId());
        voucherRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
        voucherRecordModel.setOrderId(orderId);
        voucherRecordModel.setBusinessId(order.getBusinessId());
        voucherRecordModel.setVoucherType(1);
        voucherRecordModel.setVoucherAmount(price);
        voucherRecordModel.setWriteOff(1);
        voucherRecordMapper.insert(voucherRecordModel);
        //将钱原路返回
        userModel.setVoucher(userModel.getVoucher() + price);
        userMapper.updateById(userModel);
        //修改订单状态
        order.setStatus(4);
        orderMapper.updateById(order);
        //消息盒子记录数据
        MessageBoxModel messageBoxModel = new MessageBoxModel();
        messageBoxModel.setUserId(userModel.getId());
        messageBoxModel.setQuiltUserId(userModel.getId());
        messageBoxModel.setTypeName("退款通知");
        messageBoxModel.setVoucher(activity.getPrice());
        messageBoxModel.setNotes("取消订单");
        messageBoxModel.setCreateTime(CommonHelp.getNowTimestamp());
        messageBoxModel.setOrderSn(orderId);
        messageBoxMapper.insert(messageBoxModel);
        return "取消订单成功";
    }

    @Override
    public OrderVo getBusinessOrderListUser(Integer page, Integer limit, Integer status, String businessName,
                                            Integer businessId, String beginTime, String endTime, AdminUserModel user, String areaId, String phone) {
        Page<OrderModel> orderModelPage = new Page<>(page, limit);
        Integer roleId = user.getRoleId();
        AdminUserModel adminUserModel = new AdminUserModel();
        if (roleId == 2) {
            if (adminUserModel.getBusinessId() != null) {
                businessId = adminUserModel.getBusinessId();
            }
        }
        MPJQueryWrapper<OrderModel> qw = new MPJQueryWrapper<OrderModel>()
                .selectAll(OrderModel.class)
                .select("ta.area", "tc.city", "tp.province")
                .leftJoin("tbc_areas ta on t.area_id = ta.area_id")
                .leftJoin("tbc_cities tc on ta.city_id = tc.city_id")
                .leftJoin("tbc_provinces tp on tc.province_id = tp.province_id")
                .leftJoin("tb_user tu on tu.id = t.user_id").like(StrUtil.isNotBlank(phone), "tu.phone", phone)
                .eq(StrUtil.isNotBlank(areaId), "t.area_id", areaId)
                .eq(status != null, "t.status", status)
                .eq(StringTool.isNotEmpty(businessName), "t.business_name", businessName)
                .eq(businessId != null, "t.business_id", businessId)
                .between((StrUtil.isNotBlank(beginTime) && StrUtil.isNotBlank(endTime)), "t.create_time", beginTime, endTime)
                .orderByDesc("t.id");
        Page<OrderModel> orderPage = orderMapper.selectPage(orderModelPage, qw);
        List<OrderModel> orderList = orderPage.getRecords();
        for (OrderModel orderModel : orderList) {
            orderModel.setAreaText(orderModel.getProvince() + "/" + orderModel.getCity() + "/" + orderModel.getArea());
            if (orderModel.getUserId() != null) {
                UserModel userModel = userMapper.selectById(orderModel.getUserId());
                orderModel.setUserModel(userModel);
            }
        }
        long count = orderPage.getTotal();
        OrderVo orderVo = new OrderVo();
        orderVo.setList(orderList);
        orderVo.setCount((int) count);
        return orderVo;
    }

    @Override
    public OrderVo getBusinessOrderList(Integer page, Integer limit, Integer status, String businessName, Integer businessId,
                                        String beginTime, String endTime) {
        Page<OrderModel> orderModelPage = new Page<>(page, limit);
        QueryWrapper<OrderModel> qw = new QueryWrapper<OrderModel>()
                .eq(status != null, "status", status)
                .eq(StringTool.isNotEmpty(businessName), "business_name", businessName)
                .eq(businessId != null, "business_id", businessId)
                .between((StrUtil.isNotBlank(beginTime) && StrUtil.isNotBlank(endTime)), "create_time", beginTime, endTime)
                .orderByDesc("id");
        Page<OrderModel> orderPage = orderMapper.selectPage(orderModelPage, qw);
        List<OrderModel> orderList = orderPage.getRecords();
        long count = orderPage.getTotal();
        OrderVo orderVo = new OrderVo();
        orderVo.setList(orderList);
        orderVo.setCount((int) count);
        return orderVo;
    }

    @Override
    public Object orderCumulativeVoucherAmount(Integer status, String businessName, Integer businessId, AdminUserModel user) {

        QueryWrapper<OrderModel> qw = new QueryWrapper<>();
        Integer roleId = user.getRoleId();
        AdminUserModel adminUserModel = new AdminUserModel();
        if (roleId == 2) {
            adminUserModel = adminUserService.query().eq("business_id", user.getBusinessId()).one();
        }
        if (adminUserModel.getBusinessId() != null) {
            businessId = adminUserModel.getBusinessId();
        }
        if (status != null) {
            qw.eq("status", status);
        }
        if (StringTool.isNotEmpty(businessName)) {
            qw.eq("business_name", businessName);
        }
        if (businessId != null) {
            qw.eq("business_id", businessId);
        }

        qw.orderByDesc("id");

        List<OrderModel> orderPage = orderMapper.selectList(qw);
        if (orderPage.isEmpty()) {
            return 0;
        }

        double totalVoucherAmount = orderPage.stream()
                .filter(order -> order.getStatus() != 4)
                .mapToDouble(OrderModel::getVoucher)
                .sum();
        return totalVoucherAmount;
    }

    /**
     * 不同状态的订单的数量（待收货、待发货、待使用、待评价）
     *
     * @param id
     * @return
     */
    @Override
    public Result OrderStatusCounts(Integer id) {
        OrderStatusCountsVO vo = orderMapper.OrderStatusCounts(id);
        List<Map<String,Object>> consumptionOrderList = orderMapper.getConsumptionOrderCounts(id);
        for (Map<String,Object> map : consumptionOrderList){
            String status = map.get("status")+"";
            String order_count = map.get("order_count")+"";
            if ("1".equals(status)){
                vo.setToBeUsed(vo.getToBeUsed() + Integer.parseInt(order_count));
            }else if ("2".equals(status)){
                vo.setToBeEvaluated(vo.getToBeEvaluated() + Integer.parseInt(order_count));
            }
        }
        return Result.success(vo);
    }

    @Override
    public List<BusinessModel> getOrders() {
        QueryWrapper<BusinessModel> qw = new QueryWrapper<>();
        qw.select("id", "business_name");
        return businessService.list(qw);
    }

    /**
     * 商家查询自己售卖的订单数
     * @param type 1查今天的 2时间不限
     * @param businessId
     * @param page
     * @param limit
     * @return
     */
    @Override
    public Result businessGetOrders(Integer type, Integer businessId, Integer page, Integer limit) {
        LocalDate today = LocalDate.now();
//        Integer offSet = (page - 1) * limit;
        Page<OrderModel> orderModelPage = new Page<>(page, limit);

        Wrapper<OrderModel> wq = new QueryWrapper<OrderModel>()
                .ge(type==1,"create_time", today.atStartOfDay())
                .lt(type==1,"create_time", today.plusDays(1).atStartOfDay())
                .in(type ==1,"status",3,2)
                .in(type ==2,"status",3,2)
                .eq(businessId!=null,"business_id", businessId)
                .orderByDesc("create_time");
//                .last("limit " + offSet +","+limit);
//        List<OrderModel> orderModels = orderMapper.selectList(wq);
        Page<OrderModel> orderPage = orderMapper.selectPage(orderModelPage, wq);
        List<OrderModel> orderList = orderPage.getRecords();
        for (OrderModel o:orderList
             ) {
            o.setUser(this.userMapper.selectById(o.getUserId()));
        }
        long count = orderPage.getTotal();
        OrderVo orderVo = new OrderVo();
        orderVo.setList(orderList);
        orderVo.setCount((int) count);
        if (businessId==null || businessId==0){
            orderVo.setList(null);
            orderVo.setCount(0);
            return Result.success(orderVo);
        }
        return Result.success(orderVo);
    }


    public void exportData(List<OrderModel> orderList) {
        // 对订单数据根据时间降序排序
        orderList.sort(Comparator.comparing(OrderModel::getCreateTime).reversed());
        // 设置日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
        // 格式化日期并输出
        String formattedDate = dateFormat.format(new Date());
        String fileName = "账单表" + formattedDate + ".xlsx";
        String sheetName = "账单";

        // 写入Excel文件
        EasyExcel.write(fileName, OrderModel.class).sheet(sheetName).doWrite(orderList);
    }


    @Override
    public List<OrderModel> getRollList() {
        QueryWrapper<OrderModel> orderModelQueryWrapper = new QueryWrapper<>();
        orderModelQueryWrapper.select("id", "activity_name", "user_id");
        orderModelQueryWrapper.eq("status", 2).or().eq("status", 3);
        orderModelQueryWrapper.orderByDesc("create_time");
        List<OrderModel> orderModels = orderMapper.selectList(orderModelQueryWrapper);
        for (OrderModel orderModel : orderModels) {
            if (orderModel.getUserId() != null) {
                UserModel userModel = userMapper.selectById(orderModel.getUserId());
                if (userModel != null) {
                    orderModel.setUserModel(userModel);
                }
            }
        }
        return orderModels;
    }

    /**
     * 查找订单由业务id
     *
     * @param userId 用户id
     * @return {@link Integer}
     */
    @Override
    public Integer selectOrderByBusinessId(Integer userId) {
        return this.orderMapper.selectOrderByBusinessId(userId);
    }

    @Override
    public Double incomeTime(String beginTimeDay, String endTimeDay, Integer businessId, Integer userId) {
        return orderMapper.incomeTime(beginTimeDay, endTimeDay, businessId, userId);
    }

    @Override
    public BigDecimal getTodayMyVoucher(Integer userid){
        return orderMapper.getTodayMyVoucher(userid);
    };
}
